/**
 * 530. 二叉搜索树的最小绝对差（与 783 同）
 * https://leetcode-cn.com/problems/minimum-absolute-difference-in-bst/
 */
public class Solutions_530 {
    public static void main(String[] args) {
//        TreeNode root = new TreeNode(1);
//        root.right = new TreeNode(3);
//        root.right.left = new TreeNode(2);  // output: 1

        TreeNode root = new TreeNode(4);
        root.left = new TreeNode(2);
        root.left.left = new TreeNode(1);
        root.left.right = new TreeNode(3);
        root.right = new TreeNode(6);  // output: 1

        int result = getMinimumDifference(root);
        System.out.println(result);
    }

    private static int minVal = Integer.MAX_VALUE;
    private static TreeNode preNode = null;

    public static int getMinimumDifference(TreeNode root) {
        // 在一棵二叉搜索树中，两节点的差的绝对值的最小值一定是在中序遍历的情况下，相邻两节点中产生的
        // 中序遍历
        if (root == null) {
            return minVal;
        }
        getMinimumDifference(root.left);
        if (preNode != null) {
            // 存在前一节点
            minVal = Math.min(minVal, Math.abs(root.val - preNode.val));
        }
        preNode = root;
        getMinimumDifference(root.right);
        return minVal;
    }
}
